﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using digitwhu.Logic.BusinessLogicControl;
using digitwhu.Helper;
using digitwhu.Models;
using System.IO;

namespace digitwhu.Controllers
{
    public class UserController : Controller
    {
        //获得用户信息
        [HttpGet]
        public String Default(String id)
        {
            return UserLogicControl.GetUserInfo(id);
        }
        //注册
        [HttpPost]
        public String Default(String email,String password,String nickname)
        {
            String user_id = UserLogicControl.AddUser(nickname, password, email);
            if ( int.Parse(user_id) < 0)
            {
                Response.StatusCode = 400;
            }
            return user_id;
        }
        //登录
        public String Login(String email, String password)
        {
            String userinfo = UserLogicControl.GetUserLogin(email, password);
            if (userinfo == null)
            {
                Response.StatusCode = 403;
            }
            return userinfo;
        }
        //code from stackoverflow.com
        //http://stackoverflow.com/questions/5272619/how-do-i-perform-a-ajax-jquery-upload-of-an-image-in-asp-net-mvc
        //using fileuploader.js at https://github.com/valums/file-uploader
        private String saveAvatar(String id)
        {
            bool IsIE = false;
            string sFileName = "";
            //保存目录名
            var TempFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "static/images");
            //是否上传文件
            if ((Request.Files == null) || (Request.Files.Count == 0))
            {
                if (string.IsNullOrEmpty(Request.Params["qqfile"]))
                {
                    return ("{success:false, error:'request file is empty'}");
                }
                else
                {
                    sFileName = Request.Params["qqfile"].ToString();
                }
            }
            else
            {
                sFileName = Request.Files[0].FileName;
                IsIE = true;
            }
            //上传文件是否为空
            if (string.IsNullOrEmpty(sFileName))
            {
                return ("{success:false, error:'request file is empty'}");
            }

            string DocumentName = id + Path.GetExtension(sFileName);
            //IE浏览器特殊处理代码
            if (IsIE)
            {
                try
                {
                    Request.Files[0].SaveAs(Path.Combine(TempFolder, DocumentName));
                }
                catch (Exception ex)
                {
                    return ("{success:false, error:'" + ex.Message + "'}");
                }
            }
            else
            {
                try
                {
                    if ((Request.InputStream != null) && (Request.InputStream.CanRead) && (Request.InputStream.Length > 0))
                    {
                        using (FileStream fileStream = new FileStream(Path.Combine(TempFolder, DocumentName), FileMode.Create))
                        {
                            byte[] FileBytes = new byte[Convert.ToInt32(Request.InputStream.Length) + 1];
                            Int32 bytesRead = 0;
                            bytesRead = Request.InputStream.Read(FileBytes, 0, FileBytes.Length);
                            fileStream.Write(FileBytes, 0, bytesRead);
                            fileStream.Flush();
                            fileStream.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    return ("{success:false, error:'" + ex.Message + "'}");
                }
            }

            return DocumentName;
        }

        //修改头像
        public String UpdateAvatar(String userId,String realName,String studentId,String school,String birthday,String homeAddress,String dormId,String nickName)
        {
            String avatar = this.saveAvatar(userId.ToString());
            UserLogicControl.UpdateUserInfo(userId, realName, studentId, school, birthday, homeAddress, avatar, dormId, nickName);

            return System.String.Format("{{\"avatar\":\"{0}\"}}",avatar);
        }

        //修改昵称,姓名,修改生日,修改住址,修改学校,修改学号,修改寝室
        public void UpdateUser(String userId,String realName,String studentId,String school,String birthday,String homeAddress,String avatar,String dormId,String nickName)
        {
            UserLogicControl.UpdateUserInfo(userId, realName, studentId, school, birthday, homeAddress, avatar, dormId, nickName);
        }
        //修改密码
        public String UpdatePassword(String oldPsw,String newPsw,String userId)
        {
            int result = int.Parse(UserLogicControl.UpdateUserPassword(oldPsw, newPsw, userId));
            if( result != 1 ){
                Response.StatusCode = 403;
            }
            return result.ToString();
        }

    }
    
}
